import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Message{
    public String from;
    public String to;
    public String message;

     @Override
     public String toString() {
         return "Massage[" +
                  from + " 对 " +
                 to + "说：" +
                   message  +
                 ']';
     }
 }

@WebServlet("/MessageWall")
public class MessageWall extends HttpServlet {

    //定义一个使用将JSON对象转化为Message对象的objectMapper
    private ObjectMapper objectMapper=new ObjectMapper();
    //定义一个线性表将每一次接收到的留言(Message对象)都记录起来
    List<Message> messageList=new ArrayList<>();

    //doPost方法一般用于前端传过来的提交数据
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //
        Message message=objectMapper.readValue(req.getInputStream(),Message.class);
        messageList.add(message);
        resp.getWriter().write("数据提交成功");
    }

    //用于前端加载服务器数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //设置响应报文中的数据组织格式为JSON
        resp.setContentType("application/json;charset=utf8");
        //将服务器中储存的数据信息构建成一个JSON格式的字符串
        String message=objectMapper.writeValueAsString(messageList);
        System.out.println(message);//在服务器打印一下
        //将该JSON字符串写入并构造响应报文
        resp.getWriter().write(message);

    }
}
